<?php


namespace App\Services;

use EasyWeChat\Factory;
use FoxLib\Exceptions\InternalServiceException;
use FoxLib\Services\OssService;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;

class LlsService
{
    public static function rate($mediaId, $text)
    {
        $config = config('wechat.official_account');
        $officialAccount = Factory::officialAccount($config);
        $officialAccount['cache'] = app('easyWechatCache');
        $token = $officialAccount->access_token->getToken();
        app('log')->debug($token);
        try {
            $client = new Client();
            $rpcUrl = config('service.lls_host') . "/api/ratings";
            $response = $client->request('POST', $rpcUrl,
                [
                    'json' => [
                        'accessToken' => $token['access_token'],
                        'meta' => static::getMeta($text),
                        'mediaId' => $mediaId,
                    ]
                ]
            );
            $result = json_decode($response->getBody(), true);
            app('log')->debug($result);
            $score = json_decode(base64_decode($result['result']), true);
            app('log')->debug($score);
            $stream = $officialAccount->media->get($mediaId);
            $hashName = md5(uniqid(rand(), true));
            $filename = $stream->save(storage_path('app'), $hashName);
            $armPath = storage_path('app')  . '/' . $filename;
            $mp3Path = storage_path('app')  . '/' . $hashName . '.mp3';
            exec("ffmpeg -i $armPath $mp3Path");
            $audioUri = OssService::upload($mp3Path, 'mp3');
            @unlink($armPath);
            @unlink($mp3Path);
            return [
                'uri' => $audioUri,
                'score' => $score['overall'],
            ];
        } catch (ClientException $e) {
            throw new InternalServiceException();
        }

    }

    private static function getMeta($text)
    {
        $appId = config('service.lls_app_id');
        $appSecret = config('service.lls_secret');
        $hexChars = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f'];
        $salt = time() . ':' . implode('', array_random($hexChars, 8));

        $metaInfo = [
            'item' => [
                'reftext' => $text,
                'type' => 'readaloud',
                'quality' => 7,
            ],
            'appID' => $appId,
            'salt' => $salt
        ];
        $metaPrefix = json_encode($metaInfo);
        $hash = md5($appId . $metaPrefix . $salt . $appSecret);
        return base64_encode($metaPrefix . ';hash=' . $hash);
    }
}
